package org.example.ai_chat.controller;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import org.example.ai_chat.pojo.ai_memory;
import org.example.ai_chat.pojo.ai_session;
import org.example.ai_chat.pojo.users;
import org.example.ai_chat.service.impl.UserServiceImpl;
import org.example.ai_chat.util.Result;
import org.example.ai_chat.util.ResultCodeEnum;
import org.example.ai_chat.util.pwd;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

//    @PostMapping("/session/set")
//    public Result setSession(@RequestBody ai_session session) {
//       long conversation_id=userService.setSession(session);
//        if(conversation_id<=0){
//            return Result.build(null,ResultCodeEnum.FAIL);
//        }
//        return Result.build(conversation_id, ResultCodeEnum.SUCCESS);
//    }

//    @PostMapping("/session/{id}")
//    public Result getSession(@RequestBody users user,@PathVariable int id) {
//        if(user.getUser_id()==id){
//            List<List<ai_memory>> sessions = userService.getUserMemoryById(id);
//            return Result.build(sessions, ResultCodeEnum.SUCCESS);
//
//        }
//        return Result.build(null,ResultCodeEnum.FAIL);
//    }
    @GetMapping("/")
    public Result getAllUser() {
        List<users> users = userService.getAllUser();
        if (users == null) {
            return Result.build(null, ResultCodeEnum.FAIL);
        }
        return Result.build(users, ResultCodeEnum.SUCCESS);
    }

    @GetMapping("/{id}")
    public Result getUserById(@PathVariable int id) {
        users user = userService.getUserById(id);
        if (user == null) {
            return Result.build(null, ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        return Result.build(user, ResultCodeEnum.SUCCESS);
    }

    @PostMapping("/login")
    public Result getUserByEmail(@RequestBody users user) {
        users user1 = userService.getUserByEmail(user.getEmail());
        if (userService.login(user1.getUser_id(),user.getPassword_hash())) {
            StpUtil.login(user1.getUser_id());
            StpUtil.getSession().set("userName", user1.getUsername());
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            return Result.build(user1, ResultCodeEnum.SUCCESS, tokenInfo);
        }
        return Result.build(null, ResultCodeEnum.FAIL);
    }

    @PostMapping("/addUser")
    public Result addUser(@RequestBody users user) {
        user.setPassword_hash(pwd.getSHA256Hash(user.getPassword_hash()));
        int i = userService.addUser(user);
        if (i != 0) {
            return Result.build(null, ResultCodeEnum.SUCCESS);
        }
        return Result.build(null, ResultCodeEnum.FAIL);
    }



}

